import 'dart:io';

import 'package:star_author/config/base_configuration.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/image_common_util.dart';
import 'package:star_author/utils/rouces_util.dart';
import 'package:star_author/views/stream/stream.dart';
import 'package:star_author/widgets/constraints_widget.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:video_player/video_player.dart';
import 'package:wakelock/wakelock.dart';

enum PreViewType {
  byte,
  network,
  file,
}

class PicSwiperPage extends StatefulWidget {
  static String routeName = 'pic_swiper';
  late List images;
  late int index;
  late List videos;
  bool sonance;
  PreViewType preViewType;
  List bytes;

  PicSwiperPage(
      {Key? key,
      required this.images,
      this.index = 0,
      required this.videos,
      this.preViewType: PreViewType.network,
      this.bytes: const [],
      this.sonance: false})
      : super(key: key);

  _PicSwiperPageState createState() => _PicSwiperPageState();
}

typedef DoubleClickAnimationListener = void Function();

class _PicSwiperPageState extends State<PicSwiperPage> {
  late PageController pageController;
  Color color = Colors.black;
  VideoPlayerController? player; //视频播放控制器
  bool showIcon = false; //显示播放按钮

  void onSwiperChange(v) {
    if (v >= widget.videos.length) {
      //视频暂停
      player?.pause();
      showIcon = true;
    }
    update(() {
      widget.index = v;
    });
  }

  //播放
  play() {
    showIcon = false;
    player?.play();
    update(() {});
  }

  //是否有可以播放地址
  bool get canPlay {
    return widget.videos.length > 0;
  }

  @override
  void initState() {
    super.initState();
    Wakelock.enable();
    for (dynamic video in widget.videos) {
      widget.images.insert(0, video);
    }
    pageController = PageController(initialPage: widget.index);
    init();
  }

  update(VoidCallback fn) {
    if (mounted) {
      setState(fn);
    }
  }

  /// true ？ 加载成功 ： 加载中
  bool _loadVideoOK = false;

  init() async {
    if (canPlay) {
      player = VideoPlayerController.network(
        widget.videos[0],
        httpHeaders: {HttpHeaders.userAgentHeader: "ExoPlayer"},
        ////有其他播放器播放的时候不会打断其他播放
        videoPlayerOptions: VideoPlayerOptions(mixWithOthers: true),
      );
      player?.initialize().then((_) async {
        await player?.play();
        await player?.setLooping(true);
        await player?.setVolume(widget.sonance ? 1 : 0);
        update(() {
          _loadVideoOK = true;
          showIcon = false;
        });
      }).catchError((onError) {
        LogUtil.v("视频加载失败，请查看报错：$onError  <-----报错信息到此为止");
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    try {
      player?.removeListener(() {});
      player?.dispose();
    } catch (e) {
      LogUtil.v(e.toString());
    }
    pageController.dispose();
    Wakelock.disable();
  }

  //视频播放组件
  Widget buildVideoPlayWidget(index) {
    if (canPlay) {
      if (!_loadVideoOK) {
        return ConstraintsWidget(
          width: '100vw',
          height: '100vw',
          child: Center(
              child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                StreamLoadingWidget(),
                SizedBox(
                  height: 10.w,
                ),
                Center(
                  child: Text(
                    "加载中...",
                    style: TextStyle(
                      color: ColorConf.white,
                      fontSize: 18.sp,
                    ),
                  ),
                ),
              ],
            ),
            height: Get.height,
          )),
        );
      }
    }
    return Container(
        alignment: Alignment.center,
        child: InkWell(
          child: Container(
            color: ColorConf.black,
            child: AspectRatio(
              child: VideoPlayer(player!),
              aspectRatio: player?.value.aspectRatio ?? 1,
            ),
          ),
          onTap: () {
            if (player?.value.isPlaying ?? false) {
              showIcon = true;
              update(() {});
              player?.pause();
            } else {
              Get.back();
            }
          },
        ));
  }

  @override
  Widget build(BuildContext context) {
    if ((widget.images.length) == 0) {
      return ConstraintsWidget(width: '100vw', height: '100vw');
    }
    return Container(
      width: Get.width,
      height: Get.height,
      color: color,
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          InkWell(
            child: PhotoViewGallery.builder(
              scrollPhysics: const BouncingScrollPhysics(),
              builder: (BuildContext context, int index) {
                return PhotoViewGalleryPageOptions.customChild(
                  child: Builder(
                    builder: (context) {
                      if (index < widget.videos.length) {
                        return Stack(
                          alignment: Alignment.center,
                          children: [
                            buildVideoPlayWidget(index),
                            // //是否显示播放按钮
                            Center(
                              child: Visibility(
                                visible: showIcon,
                                child: InkWell(
                                  child: RoucesUtil.getAssetsIcon(
                                      'common/play', 80),
                                  onTap: () {
                                    play();
                                  },
                                ),
                              ),
                            ),
                          ],
                        );
                      }
                      Map<PreViewType, Widget> map = {
                        PreViewType.network: GestureDetector(
                          child: CachedNetworkImage(
                              imageUrl: widget.images[index],
                              placeholder: (BuildContext context, String url) {
                                return buildLogo();
                              }),
                          onLongPress: () {
                            showDialog(widget.images[index]);
                          },
                        ),
                        PreViewType.byte: GestureDetector(
                          child: widget.bytes.length == 0
                              ? buildLogo()
                              : Image.memory(widget.bytes[index]),
                          onLongPress: () {
                            showDialog(widget.images[index]);
                          },
                        ),
                      };
                      LogUtil.v("preViewType:${widget.preViewType}");
                      return map[widget.preViewType] ??
                          GestureDetector(
                            child: CachedNetworkImage(
                                imageUrl: widget.images[index],
                                placeholder:
                                    (BuildContext context, String url) {
                                  return buildLogo();
                                }),
                            onLongPress: () {
                              showDialog(widget.images[index]);
                            },
                          );
                    },
                  ),
                  initialScale: PhotoViewComputedScale.contained * 1,
                  heroAttributes:
                      PhotoViewHeroAttributes(tag: widget.images[index]),
                );
              },
              itemCount: widget.images.length,
              backgroundDecoration: BoxDecoration(color: color),
              pageController: pageController,
              onPageChanged: (index) {
                onSwiperChange(index);
              },
            ),
            onTap: () {
              Get.back();
            },
          ),
          Positioned(

              ///布局自己换
              top: MediaQuery.of(context).padding.top,
              child: Center(
                child: Container(
                  child: Text(
                    '${widget.index + 1}/${widget.images.length}',
                    style: TextStyle(color: Colors.white, fontSize: 18.sp),
                  ),
                  alignment: Alignment.topCenter,
                ),
              ))
        ],
      ),
    );
  }

  Widget buildLogo() {
    return Container(
      width: Get.width,
      height: Get.height,
      decoration: BoxDecoration(
        color: ColorConf.lightGray,
        borderRadius: BorderRadius.circular(12.w),
        image: DecorationImage(
          scale: 2,
          image: const AssetImage('images/lt_common/temp_load.png'),
        ),
      ),
    );
  }

  showDialog(url) async {
    await showCupertinoModalPopup(
      context: context,
      builder: (context) {
        return CupertinoActionSheet(
          title: Text('操作'),
          actions: <Widget>[
            CupertinoActionSheetAction(
              child: Text('保存图片'),
              onPressed: () {
                ImageCommonUtil.saveImage(url, callback: () {
                  Get.back();
                });
              },
              isDefaultAction: false,
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            child: Text('取消'),
            onPressed: () {
              Navigator.of(context).pop('cancel');
            },
          ),
        );
      },
    );
  }
}
